package weiy.top.modules.category.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import weiy.top.modules.category.entity.PmsCategory;
import weiy.top.modules.category.mapper.PmsCategoryMapper;
import weiy.top.modules.category.service.IPmsCategoryBrandRelationService;
import weiy.top.modules.category.service.IPmsCategoryService;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import weiy.top.vo.CascadeVo;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: pms_category
 * @Author: weihancheng
 * @Date: 2021-11-24
 * @Version: V1.0
 */
@Service
public class PmsCategoryServiceImpl extends ServiceImpl<PmsCategoryMapper, PmsCategory> implements IPmsCategoryService {

    @Autowired
    private IPmsCategoryBrandRelationService categoryBrandRelationService;

    @Override
    public List<PmsCategory> tree() {
        List<PmsCategory> entities = baseMapper.selectList(null);
        return entities.stream().filter(entity -> StringUtils.isEmpty(entity.getParentCid()) || entity.getParentCid().equals("0"))
                .map(entity -> entity.setChildren(getChildren(entity, entities)))
                .sorted(Comparator.comparingInt(PmsCategory::getSort))
                .collect(Collectors.toList());
    }

    private List<PmsCategory> getChildren(PmsCategory root, List<PmsCategory> all) {
        return all.stream()
                .filter(entity -> entity.getParentCid().equals(root.getCatId()))
                .map(entity -> entity.setChildren(getChildren(entity, all)))
                .sorted(Comparator.comparingInt(PmsCategory::getSort))
                .collect(Collectors.toList());
    }

    /**
     * 返回适用于antdv格式的tree数据，目的是方便前端控件的迁移。之后只需要修改其他项目的后端输出即可
     */
    @Override
    public List<PmsCategory> antdvTree() {
        List<PmsCategory> entities = baseMapper.selectList(null);

        // 批量设置title, key
        entities.forEach(entity -> {
            entity.setKey(entity.getCatId());
            entity.setTitle(entity.getName());
            entity.setLevel(entity.getCatLevel());
        });

        return entities.stream().filter(entity -> StringUtils.isEmpty(entity.getParentCid()) || entity.getParentCid().equals("0"))
                .map(menu -> menu.setChildren(getChildren(menu, entities)))
                .sorted(Comparator.comparingInt(PmsCategory::getSort))
                .collect(Collectors.toList());
    }


    @Override
    public void saveMain(PmsCategory pmsCategory) {
        String parentCid = pmsCategory.getParentCid();
        int catLevel = 0;
        if (parentCid == null) {
            pmsCategory.setParentCid("0");
        } else {
            PmsCategory parentEntity = getByIdMain(parentCid);
            catLevel = parentEntity.getCatLevel() + 1;
        }
        pmsCategory.setCatLevel(catLevel);

        // 查询当前等级的最大排序数值并加一 （这里多线程可能会出现问题，但是无所谓，这里的数据准确性并不太重要）
        Integer sort = generateSortByLevel(catLevel);
        pmsCategory.setSort(sort);

        this.save(pmsCategory);
    }

    private Integer generateSortByLevel(Integer catLevel) {
        LambdaQueryWrapper<PmsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PmsCategory::getCatLevel, catLevel);
        queryWrapper.orderByDesc(PmsCategory::getSort);
        queryWrapper.last("limit 1");
        PmsCategory category = this.getOne(queryWrapper);
        if (category == null) {
            return 1;
        }
        Integer sort = category.getSort();
        return sort + 1;
    }

    @Override
    public void removeByCatIds(List<String> ids) {
        LambdaQueryWrapper<PmsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(PmsCategory::getCatId, ids);
        this.remove(queryWrapper);
    }

    @Override
    public PmsCategory getByIdMain(String catId) {
        LambdaQueryWrapper<PmsCategory> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(PmsCategory::getCatId, catId);
        return this.getOne(queryWrapper);
    }

    @Override
    public void updateBatchMain(List<PmsCategory> pmsCategoryList) {
        updateBatchById(pmsCategoryList);
    }

    @Override
    public void updateByIdMain(PmsCategory pmsCategory) {
        updateById(pmsCategory);
        categoryBrandRelationService.updateAllCategory(pmsCategory.getCatId(), pmsCategory.getName());
    }

    @Override
    public String[] getCatelogPathByCatelogId(String catelogId) {
        List<String> paths = new ArrayList<>();
        List<String> parentPath = findParentPath(catelogId, paths);
        //进行一个逆序排列
        Collections.reverse(parentPath);
        // List转数组
        return parentPath.toArray(new String[0]);
    }

    @Override
    public List<CascadeVo> getCascadeTree() {
        List<PmsCategory> entities = baseMapper.selectList(null);
        return entities.stream().filter(entity -> StringUtils.isEmpty(entity.getParentCid()) || entity.getParentCid().equals("0"))
                .sorted(Comparator.comparingInt(PmsCategory::getSort))
                .map(entity -> {
                    CascadeVo cascadeVo = new CascadeVo();
                    cascadeVo.setLabel(entity.getName());
                    cascadeVo.setValue(entity.getCatId());
                    cascadeVo.setChildren(getCascadeChildren(entity, entities));
                    return cascadeVo;
                })
                .collect(Collectors.toList());
    }

    private List<CascadeVo> getCascadeChildren(PmsCategory root, List<PmsCategory> all) {
        return all.stream()
                .filter(entity -> entity.getParentCid().equals(root.getCatId()))
                .sorted(Comparator.comparingInt(PmsCategory::getSort))
                .map(entity -> {
                    CascadeVo cascadeVo = new CascadeVo();
                    cascadeVo.setLabel(entity.getName());
                    cascadeVo.setValue(entity.getCatId());
                    cascadeVo.setChildren(getCascadeChildren(entity, all));
                    return cascadeVo;
                })
                .collect(Collectors.toList());
    }

    private List<String> findParentPath(String catelogId, List<String> paths) {

        //1、收集当前节点id
        paths.add(catelogId);

        //根据当前分类id查询信息
        PmsCategory entity = this.getById(catelogId);
        //如果当前不是父分类
        if (!entity.getParentCid().equals("0")) {
            findParentPath(entity.getParentCid(), paths);
        }

        return paths;
    }


}
